package com.sctvcloud.zhaohua_sd.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.beans.ADynamicsItem;
import com.sctvcloud.zhaohua_sd.beans.SingleResult;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.DMethods;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.http.ParamsEditor;
import com.sctvcloud.zhaohua_sd.ui.adapter.AnchorCircleAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.holder.AnchorCircleHolder;
import com.sctvcloud.zhaohua_sd.ui.dialog.DeleteDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.utils.SkipUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.utils.ListTypeUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 我的主播动态页
 */
public class MyAnchorDyActivity extends BaseActivity implements OnItemInternalClick
        , CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    private final String TAG_DELETE = "tag_delete";
    public static final int INTO_NEWSINFO = 1;
    public static final String INTO_ANCHORINFO_ISDIGG = "info_isDigg";

    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    @BindView(R.id.my_anchor_refresh)
    protected CanRefreshLayout refreshLayout;

    private Unbinder unbinder;

    private AnchorCircleAdapter adapter;

    private int allCount = 1;
    private int pageIndex = -1;
    private int selectedToInfoIndex = 0;
    private boolean haseUpdateVersion;

    protected String contentVideoUrl;

    private BaseDialogFragment.ICallBack deleteCallback = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg != null) {
                deleteItem(msg.what);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_my_anchor_dy);
        unbinder = ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (adapter != null) {
            adapter.onDestory();
            adapter = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onLoginSuc() {
        refreshLayout.autoRefresh();
    }

    @Override
    public void onItemInternalClick(View itemView, View view, int position) {
        switch (view.getId()) {

            case R.id.item_anchor_home_delete:
                DeleteDiaFragment ddf = new DeleteDiaFragment();
                ddf.setPosition(position);
                ddf.setCallBack(deleteCallback);
                ddf.show(getSupportFragmentManager(), TAG_DELETE);

                break;
            case R.id.item_anchor_home_dynamics_video_play:
                ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
                contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
                SkipUtil.skipToVideoPlay(MyAnchorDyActivity.this, contentVideoUrl, dynamics.getPlayedPos(), position);
                break;
            case R.id.tv_anchor_up:
                if (!UserManager.isLoginS()) {
                    toLogin();
                    return;
                }
                ADynamicsItem dyUp = (ADynamicsItem) adapter.getItem(position);
//                if (dyUp.getAttitudesStatus()) {
//                    toast("已经点过赞啦");
//                    return;
//                }
                doUp(dyUp, position);
                break;
            case R.id.tv_anchor_comment:
                selectedToInfoIndex = position;
                ADynamicsItem adi = (ADynamicsItem) adapter.getItem(position);
                Intent intent = new Intent(MyAnchorDyActivity.this, CommentDetailActivity.class);
                intent.putExtra(EX_DATA, adi);
                intent.putExtra(EX_COMMENT_TYPE, 3);
                startActivityForResult(intent, INTO_NEWSINFO);
                break;
        }

    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
            toast(R.string.refreshing_please_waite);
            return;
        }
        if (adapter == null) {
            getDatas(0);
        } else {
            getDatas(pageIndex + 1);
        }
    }

    @Override
    public void onRefresh() {
        if (refreshLayout.isLoading()) {
            refreshLayout.refreshComplete();
            toast(R.string.loading_data_wait);
            return;
        }
        getDatas(0);
    }

    private void getDatas(int index) {
        if (index < 0) {
            index = 0;
        }
        if (index >= allCount) {
            completRefresh();
            return;
        }
        if (!UserManager.isLoginS()) {
            completRefresh();
            toLogin();
            return;
        }
        ParamsEditor pe = new ParamsEditor();
//        pe.put("capacity", 15);
        pe.put("index", index);
        pe.put("siteNumber", Constances.SITE_ID);
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        NetUtils.getNetAdapter().getMyAnchorDynamicList(getOwnerName()
                , pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsListNetCallback<ADynamicsItem>(ListTypeUtils.ADynamicItem(), index) {
                    @Override
                    public void onSuc(List<ADynamicsItem> aDynamicsItems) {
                        setData(aDynamicsItems, calledIndex == 0);
                        pageIndex = calledIndex;
                        allCount = getPageResponse().getData().getPageAll();
                        if (adapter == null || adapter.getItemCount() >= allCount) {
                            refreshLayout.setLoadMoreEnabled(false);
                        } else {
                            refreshLayout.setLoadMoreEnabled(true);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        super.onError(ex, errorMsg, netCode);
                        setData(null, calledIndex == 0);
                        if (calledIndex == 0) {
                            if (pageIndex > 0) {
                                pageIndex = -1;
                            }
                            refreshLayout.setLoadMoreEnabled(false);
                        }
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        completRefresh();
                    }
                });
    }

    private AnchorCircleHolder lastHolder;
    private List<ADynamicsItem> dyDatas = new ArrayList<>();

    private void doUp(final ADynamicsItem aDynamicsItem, int position) {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(position);
//        AnchorHomeDynamicsHolder lastHolder = null;
        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof AnchorCircleHolder) {
            lastHolder = (AnchorCircleHolder) recyclerView.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.getTvUp().setDrawableEnlarge();
            }
        }

        ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
        pe.put("dynamicId", aDynamicsItem.getDynamicId());
        pe.put("fType", 1);//1 主播 2报料 3新闻(短视频) 4 直播
//        pe.put("token", UserManager.getInstance().getToken());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());

        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {
                    SkipUtil.skipToAddUserOperate(MyAnchorDyActivity.this, getOwnerName(), 13, 2, "主播圈点赞", aDynamicsItem.getDynamicId(), Cache.getInstance().getCurrentChannelId());
                    for (ADynamicsItem item : dyDatas) {
                        if (item.getDynamicId().equals(aDynamicsItem.getDynamicId())) {
                            item.setAttitudesCount(aDynamicsItem.getAttitudesStatus() ? aDynamicsItem.getAttitudesCount() - 1 : aDynamicsItem.getAttitudesCount() + 1);
                            item.setAttitudesStatus(!aDynamicsItem.getAttitudesStatus());
                            adapter.notifyDataSetChanged();
                            if (item.getAttitudesStatus()) {
                                addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                            }
                        }
                    }
                }
            }
        });
    }

    private void deleteItem(int position) {
        if (!UserManager.isLoginS()) {
            toLogin();
            return;
        }
        if (position >= 0 && position < adapter.getItemCount()) {
            showProgress(getString(R.string.msg_please_wait), false);
            ADynamicsItem adi = adapter.getItem(position);
            ParamsEditor pe = new ParamsEditor();
            pe.put("dynamicId", adi.getDynamicId());
            pe.put("siteNumber", Constances.SITE_ID);
            pe.put("userId", UserManager.getInstance().getUser().getUserId());
            NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.DeleteDynamics
                    , pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class, position) {
                        @Override
                        public void onSuc(SingleResult singleResult) {
                            if (singleResult != null && singleResult.isSuccess()) {
                                onDeleteSuc(int1);
                            } else {
                                toast(R.string.delete_failed);
                            }
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
                            toast(R.string.delete_failed);
                        }

                        @Override
                        public void onEnd() {
                            super.onEnd();
                            closeProgress();
                        }
                    });
        }
    }

    private void completRefresh() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
    }

    private void onDeleteSuc(int pos) {
        toast(R.string.delete_suc);
        adapter.removeByPostion(pos);
        if (!haseUpdateVersion) {
            haseUpdateVersion = true;
            mApplication.getDatasVersionManager().updateVersion(Constances.DATA_VERSION_ADYNAMIC);
        }
        allCount--;
    }

    private synchronized void setData(List<ADynamicsItem> list, boolean isReset) {
        if (adapter == null) {
            dyDatas.clear();
            dyDatas.addAll(list);
            adapter = new AnchorCircleAdapter(this, list);
            adapter.setCanDelete(true);
            adapter.setItemInternalClick(this);
            recyclerView.setAdapter(adapter);
        } else {
            if (isReset) {
                dyDatas.clear();
                dyDatas.addAll(list);
                adapter.setData(list);
            } else {
                if (ListUtils.isListValued(list)) {
                    dyDatas.addAll(list);
                    adapter.addDatas(list);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == INTO_NEWSINFO) {
                ADynamicsItem item = dyDatas.get(selectedToInfoIndex);
                boolean isDigg = data.getBooleanExtra(INTO_ANCHORINFO_ISDIGG, false);
                if (isDigg != item.getAttitudesStatus()) {
                    RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View lastView = manager.findViewByPosition(selectedToInfoIndex);
                    AnchorCircleHolder lastHolder = null;
                    if (null != lastView) {
                        lastHolder = (AnchorCircleHolder) recyclerView.getChildViewHolder(lastView);
                    }
                    if (isDigg) {
                        dyDatas.get(selectedToInfoIndex).setAttitudesCount(item.getAttitudesCount() + 1);
                        if (null != lastHolder) {
                            Drawable drawable = MyAnchorDyActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            lastHolder.getTvUp().setDrawables(drawable, null, null, null);
                            lastHolder.getTvUp().setTextColor(MyAnchorDyActivity.this.getResources().getColor(R.color.colorRedMain));
                            lastHolder.getTvUp().setText("" + dyDatas.get(selectedToInfoIndex).getAttitudesCount());
                        }
                    } else {
                        dyDatas.get(selectedToInfoIndex).setAttitudesCount(item.getAttitudesCount() - 1);
                        if (null != lastHolder) {
                            Drawable drawable = MyAnchorDyActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            lastHolder.getTvUp().setDrawables(drawable, null, null, null);
                            lastHolder.getTvUp().setTextColor(MyAnchorDyActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
                            lastHolder.getTvUp().setText("" + dyDatas.get(selectedToInfoIndex).getAttitudesCount());
                        }
                    }
                    dyDatas.get(selectedToInfoIndex).setAttitudesStatus(isDigg);
                    adapter.setData(dyDatas);
                }
            }
        }
    }

}
